package com.wefans.wefansapp.activity;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.BenefitData;
import com.wefans.wefansapp.common.tool.data.BenefitResponseData;
import com.wefans.wefansapp.common.tool.data.BenefitVoteData;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetImage;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;
import com.wefans.wefansapp.common.tool.preference.MFSharedPreference;

public class BenefitActivity extends BaseActivity implements IOnNetworkListener {

	private BenefitData mBenefitItems = new BenefitData();
	private BenefitVoteData mBenefitVoteDate = new BenefitVoteData();
	private ArrayList<BenefitResponseData> mBenefitResponseData = new ArrayList<BenefitResponseData>();
	private CBenefitAdaptor mBenefitAdapter = null;
	private ListView mLvBenefit = null;
    private DrawerLayout   m_DrawerLayout  = null;
    private FrameLayout    m_DrawerView    = null;
    private Intent it = new Intent();
    private MFNetworkManager m_oNetworManager = null;
    private MFDataManager    m_oDataManager   = null;
    private MFSharedPreference msp = null;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		setContentView(R.layout.activity_benefit);
		initialize();
        installEvent();
		
        msp = new MFSharedPreference(this);
		setTitle("Benefit");
		

		//setDummy();
		//mLvBenefit.setAdapter(mBenefitAdapter);

	}
	
    @Override
    protected void onPause()
    {
        MFDebug.d(">> onPause()");
        
        notifyDoClaseDrawerMenu();
        
        super.onPause();
    }
	
    @Override
    protected void notifyDoClaseDrawerMenu()
    {
        MFDebug.d(">> notifyDoClaseDrawerMenu()");
        
        super.notifyDoClaseDrawerMenu();
        
        if( m_DrawerLayout == null ) {
            MFDebug.e(new Exception("There are NO Drawer-Layout"));
            return;
        }
        
        if( m_DrawerView == null ) {
            MFDebug.e(new Exception("There are NO Drawer-View"));
            return;
        }
        
        m_DrawerLayout.closeDrawer(m_DrawerView);
        m_sdQuickMenu.close();
    }
	
	@Override
    public void onClick(View v)
    {
        MFDebug.d(">> onClick()");
        
        switch( v.getId() ) {
        	case R.id.TV_BENEFIT_SEND:
        		it = new Intent(getApplicationContext(), BenefitUserActivity.class);
    			startActivityForResult(it,v.getId());
            case R.id.IB_BENEFIT_HEADER_LEFT_BUTTON :
                m_DrawerLayout.openDrawer(m_DrawerView);
                break;
             default :
                break;
        }
        
        super.onClick(v);
    }
	
    private void initialize()
    {
        MFDebug.d(">> initialize()");
        
        m_oNetworManager = MFNetworkManager.getInstance(this);
        m_oDataManager   = MFDataManager.getInstance(this);
//        if(msp.getMem_idx()==null){
        	RequestServerBenefitData("42750");
//        }else{
//        	RequestServerBenefitData(msp.getMem_idx());
//        }
        //Contents layout adding
        FrameLayout containerContents = (FrameLayout) findViewById(R.id.FL_BENEFIT_CONTAINER);
        addContentsLayout(containerContents, R.layout.layout_benefit);
        addQuickMenuLayout(containerContents);
        
        //Drawer menu adding
        m_DrawerView = (FrameLayout) findViewById(R.id.FL_BENEFIT_DRAWER_LAYOUT);
        addDrawerLayout(m_DrawerView);
        
        //set drawer layout (root)
        m_DrawerLayout = (DrawerLayout) findViewById(R.id.DL_BENEFIT_NAVIGATION_LAYOUT);
    }
    
    private void installEvent()
    {
        MFDebug.d(">> installEvent()");
        
        ((ImageButton) findViewById(R.id.IB_BENEFIT_HEADER_LEFT_BUTTON)).setOnClickListener(this);
        
    }
    
	private void RequestServerBenefitData(String mem_idx){
		 m_oNetworManager.requestBenfit(mem_idx, this);	
	}
		
	private void RequestServerBenefitVoteData(String mem_idx, String event_idx, String num){
		m_oNetworManager.requestBenfitVote(mem_idx, event_idx, num, this);

	}

	//network interface
    @Override
    public void onNetMessage(int resultCode, NetMessage message)
    {
        MFDebug.d(">> onNetMessage()");
        MFDebug.d("++ resultCode : " + resultCode);
        MFDebug.d("++ message : " + message);
        
        try {
            //서버 여동 데이터
            if( message instanceof NetJsonData ) {
                long magicNum = ((NetJsonData) message).getMagicNum();
                String json = ((NetJsonData) message).getResponseJson();
                
                if( json == null ) {
                    throw new Exception("invalid json data");
                }
                
                Gson gson = new Gson();
                Toast toastVote;
                
                if( magicNum == MFNetworkManager.REQUEST_BENEFIT ) {
                	mBenefitItems = (BenefitData)gson.fromJson(json, BenefitData.class);
                    if( mBenefitItems == null ) {
                        throw new Exception("Gson parsing error");
                    }
                    m_oDataManager.setBenefitData(mBenefitItems);
                    mBenefitResponseData.clear();
            		mBenefitResponseData = (ArrayList<BenefitResponseData>) mBenefitItems.getData().clone();
            		mLvBenefit = (ListView) findViewById(R.id.LV_BENEFIT);
            		String bkColor = new String("#FEF2DC");
            		mLvBenefit.setBackgroundColor(Color.parseColor(bkColor));
            			
            		mBenefitAdapter = new CBenefitAdaptor(this, R.layout.list_item_benefit, mBenefitResponseData);
            		mBenefitAdapter.notifyDataSetChanged();
            		mLvBenefit.setAdapter(mBenefitAdapter);
                } else if( magicNum == MFNetworkManager.REQUEST_BENEFIT_VOTE ) {
                	mBenefitVoteDate = (BenefitVoteData)gson.fromJson(json, BenefitVoteData.class);
                    if( mBenefitVoteDate == null ) {
                        throw new Exception("Gson parsing error");
                    }
                    if( mBenefitVoteDate.getResultcode().equals("1") ){
                    	toastVote = Toast.makeText(this, getString(R.string.benefit_vote_success), Toast.LENGTH_LONG);
                    }else{
                    	toastVote = Toast.makeText(this, mBenefitVoteDate.getErrorcode() + ":" + getString(R.string.benefit_vote_fail), Toast.LENGTH_LONG);
                    }
                    toastVote.show();
                }
                
            }
            //이미지 데이터
            else if( message instanceof NetImage ) {
                
            }
            else {
                //ignore...
            }
        } catch(Exception e) {
            MFDebug.e(e);
        }
    }
 
    private void setDummy(){
    	BenefitResponseData dummy = new BenefitResponseData();
    	dummy.setImg_url("http://img.wefansapp.com/fandomschool_v3/plus/banner/lunch_main_86.jpg");
    	dummy.setTitle("빅스 홍빈 생일축하광고 9월 29일자 스포츠서울신문 (90명)");
    	dummy.setMy_cnt("3");
    	dummy.setTot_mem_cnt("31501");
    	dummy.setIs_open("30");
    	
    	mBenefitResponseData.add(dummy);
    	dummy = new BenefitResponseData();
    	dummy.setImg_url("http://img.wefansapp.com/fandomschool_v3/plus/banner/lunch_main_86.jpg");
    	dummy.setTitle("빅스 홍빈 생일축하광고 9월 29일자 스포츠서울신문 (90명)");
    	dummy.setMy_cnt("3");
    	dummy.setTot_mem_cnt("31501");
    	dummy.setIs_open("30");
    	
    	mBenefitResponseData.add(dummy);
    	dummy.setImg_url("http://img.wefansapp.com/fandomschool_v3/plus/banner/lunch_main_86.jpg");
    	dummy.setTitle("빅스 홍빈 생일축하광고 9월 29일자 스포츠서울신문 (90명)");
    	dummy.setMy_cnt("3");
    	dummy.setTot_mem_cnt("31501");
    	dummy.setIs_open("30");
    	
    	mBenefitResponseData.add(dummy);
    	dummy.setImg_url("http://img.wefansapp.com/fandomschool_v3/plus/banner/lunch_main_86.jpg");
    	dummy.setTitle("빅스 홍빈 생일축하광고 9월 29일자 스포츠서울신문 (90명)");
    	dummy.setMy_cnt("3");
    	dummy.setTot_mem_cnt("31501");
    	dummy.setIs_open("30");
    	
    	mBenefitResponseData.add(dummy);
    }
    
    private class CBenefitAdaptor extends ArrayAdapter<BenefitResponseData>{

    	private Context                                m_ctx         = null;                           
        private ArrayList<BenefitResponseData>   	   m_alsItems    = null;
        
        
    	public CBenefitAdaptor(Context ctx, int nResID, ArrayList<BenefitResponseData> aylsItems) {
            super(ctx, nResID, aylsItems);
            MFDebug.d(">> BenefitAdaptor::BenefitAdaptor(ctx, nResID, aylsItems) ");
            this.m_ctx       = ctx;
            this.m_alsItems  = aylsItems;
        }
    	
    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		MFDebug.d(">> Benefit::getView()");
    		MFDebug.d("++ position=" + position);
    		MFDebug.d("++ convertView=" + convertView);
            MFDebug.d("++ parent=" + parent);

            final BenefitResponseData dBeneResponsefitData = m_alsItems.get(position);
            
            LayoutInflater inflater = (LayoutInflater)m_ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            ViewHolder vh = new ViewHolder();
            
            View v = convertView;
            v = inflater.inflate(R.layout.list_item_benefit, null);
            
			vh.ivBenfitImage 	= (ImageView) v.findViewById(R.id.IV_BENEFIT_IMG);
			vh.tvDescription 	= (TextView) v.findViewById(R.id.TV_BENEFIT_DESC);
			vh.tvVote           = (TextView) v.findViewById(R.id.TV_BENEFIT);
			vh.tvDday        	= (TextView) v.findViewById(R.id.TV_DDAY);
			vh.tvBenefitSend 	= (TextView) v.findViewById(R.id.TV_BENEFIT_SEND);
			v.setTag(vh);
    		
    		vh.ivBenfitImage.setImageDrawable(LoadImageFromWebURL(dBeneResponsefitData.getImg_url()));
    		vh.tvDescription.setText(dBeneResponsefitData.getBenefit_title());
    		String vote_count = this.getContext().getString(R.string.benefit_cnt)+ " : " + dBeneResponsefitData.getMy_cnt() + " | " +
    							this.getContext().getString(R.string.benefit_vote_cnt) + " : " + dBeneResponsefitData.getTot_mem_cnt();
    		vh.tvVote.setText(vote_count);
    		vh.tvDday.setText(dBeneResponsefitData.getIs_open()+"D");
    		vh.tvBenefitSend.setText(this.getContext().getString(R.string.benefit_send));
    		
    		vh.ivBenfitImage.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
		   	        MFDebug.d("++ v.getId() : " + "IV_BENEFIT_IMG");
					Intent it = new Intent(getContext(), BenefitDetailActivity.class);
					
					//todo member회원키 얻어오는 부분 추가 필요
					it.putExtra("idx", dBeneResponsefitData.getIdx());
					m_ctx.startActivity(it);
				}
			});
    		vh.tvBenefitSend.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
	    	        MFDebug.d("++ v.getId() : " + "TV_BENEFIT_SEND");
	    	        RequestServerBenefitVoteData(m_oDataManager.getMebmerIdx(),dBeneResponsefitData.getIdx(),"1");
				}
			});
    		
            return v;
        }
    	
    	private Drawable LoadImageFromWebURL(String url){
    		try{
    			InputStream is = (InputStream) new URL(url).getContent();
    			Drawable d = Drawable.createFromStream(is,"src name");
    			return d;
    		}catch (Exception e){
    			MFDebug.d(">> LoadImageFromWebURL() error: " + e);
    			return null;
    		}
    	}
    	   
        
        public class ViewHolder
        {
        	ImageView ivBenfitImage 	= null;
            TextView  tvDescription  	= null;
            TextView  tvVote 			= null;
            TextView  tvDday		    = null;
            TextView  tvBenefitSend		= null;
        }
    }
}